package com.doyens.gateway.filter;

import com.doyens.auth.utils.CookieUtils;
import com.doyens.auth.utils.JwtUtils;
import com.doyens.gateway.config.FilterProperties;
import com.doyens.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;


    // 过滤的时间  pre  post  error
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器的顺序 值越小越优先
    @Override
    public int filterOrder() {
        return 10;
    }

    //是否执行过滤器
    @Override
    public boolean shouldFilter() {
        List<String> allowPaths = this.filterProperties.getAllowPaths();
        //通过RequestConttext获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String url = request.getRequestURL().toString();
        for (String allowPath : allowPaths) {
            if (StringUtils.contains(url,allowPath)){
                return false; //不执行过滤器
            }
        }

        return true;
    }

    //过滤器业务逻辑
    @Override
    public Object run() throws ZuulException {
        //通过RequestConttext获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();


        //从cookie中获取token码
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());

      /*  if(StringUtils.isBlank(token)){
            context.setSendZuulResponse(false);//设置不能不通过
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());//设置返回状态码
        }*/
        //解析token码
        try {
            JwtUtils.getInfoFromToken(token,this.jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            context.setSendZuulResponse(false);//设置不能不通过
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());//设置返回状态码
        }
        return null;
    }
}
